package com.anche.cywebnew.Service.auditManager.impl;

import cn.hutool.core.util.StrUtil;
import com.anche.cywebnew.DAO.auditManager.OperateLogMapper;
import com.anche.cywebnew.Pojo.auditManager.LogInfo;
import com.anche.cywebnew.Pojo.systemManager.SysUser;
import com.anche.cywebnew.Service.auditManager.OperateLogService;
import com.anche.cywebnew.Service.securityManager.SecurityLogService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class OperateLogServiceImpl implements OperateLogService {

    @Autowired
    private OperateLogMapper operateLogMapper;

    @Autowired
    private SecurityLogService securityLogService;

    @Override
    public Page<LogInfo> getOperateLogPager(Integer page, Integer limit, LogInfo logInfo) {
        Map<String, Object> condit = new HashMap<>();
        if(StrUtil.isNotEmpty(logInfo.getOperate_time())){
            String[] times = logInfo.getOperate_time().split(" - ");
            if(times.length == 2){
                condit.put("starttime", times[0].replace("-", "").replace(" ", "") + "000000");
                condit.put("endtime", times[1].replace("-", "").replace(" ", "") + "235959");
                logInfo.setOperate_time(null);
            }else {
                condit.put("operate_time", logInfo.getOperate_time());
            }
        }
        condit.put("organization", logInfo.getOrganization());
        condit.put("user_name", logInfo.getUser_name());
        condit.put("terminal_id", logInfo.getTerminal_id());

        Page<LogInfo> page1 = PageHelper.startPage(page, limit);
        List<LogInfo> logInfos = operateLogMapper.selectOperateLogList(condit);
        SysUser sysUser = (SysUser) SecurityUtils.getSubject().getPrincipal();
        for (LogInfo log : logInfos) {
            String jyw = DigestUtils.md5Hex(log.getUser_id() + log.getOperate_type() + log.getOperate_time() + log.getOperate_result());
            if (!jyw.equals(log.getJyw())){
                log.setIsupdate(1);
                securityLogService.insertSecurityLog("数据篡改", "查询操作日志【" + log.getNum_id() + "】信息时发现数据被篡改", sysUser);
            }
        }
        return page1;
    }

    @Override
    public List<Map<String, String>> getOperateLogStat() {
        return operateLogMapper.selectOperateLogStat(null, null);
    }

}
